<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * 后台系统初始化
 * 
 * @author  : $Author: spike $
 * @date    : $Date: 2014-03-03 17:00:52 +0800 (一, 2014-03-03) $
 * @version : $Id: sys_init.php 52 2014-03-03 09:00:52Z spike $
 * @rev     : $Revision: 52 $
 */
class Sys_init
{
    private $_directory;
    private $_class;
    private $_method;
    private $_key;
    private $_error;
    private $_router;

    // 直接通过规则（无需登录）, 留空为必须为空, *为任意值
    private $_ignore = array(
        array(
            'directory' => '',
            'class'     => 'home',
            'method'    => 'login',
        ),
        array(
            'directory' => '',
            'class'     => 'home',
            'method'    => 'logout',
        ),
    );


    // 公共权限（登陆后自带）
    private $_public = array(
        'home/index',
        'home/phpinfo',
        'center/profile',
        'center/change_password',
        'center/upload_avatar',
    );

    // 是否验证权限
    private $_check_priv  = TRUE;   

    // 最大保存的访问记录
    private $_max_history = 10;

    /**
     * Constructor
     */
    public function init()
    {
        require_once(APPPATH.'helpers/common_helper.php');

        $this->_router = & load_class('Router', 'core');
        $this->_error  = & load_class('Exceptions', 'core');
        $this->_input  = & load_class('Input', 'core');


        $this->_directory = trim($this->_router->directory, "/");
        $this->_class     = $this->_router->class;
        $this->_method    = $this->_router->method;
        $this->_key       = $this->_directory ? "{$this->_directory}/{$this->_class}/{$this->_method}" : "{$this->_class}/{$this->_method}";

        if( TRUE === $this->_is_ignore())
            return;

        $this->_check_priv();
        $this->_check_browser();
        $this->_record_breadcrumb();
    }

    /**
     * [是否满足忽略的条件]
     */
    protected function _is_ignore()
    {
        if( ! $this->_ignore || ! is_array($this->_ignore))
        {
            return FALSE;
        }

        $flag = FALSE;
        foreach ($this->_ignore as $rule) 
        {
            if( $rule['directory'] !== '*' && $rule['directory'] !== $this->_directory)
            {
                continue;
            }

            if( $rule['class'] !== '*' && $rule['class'] !== $this->_class)
            {
                continue;
            }

            if( $rule['method'] !== '*' && $rule['method'] !== $this->_method)
            {
                continue;
            }

            $flag = TRUE;
            break;
        }
        return $flag;
    }

    /**
     * 检测浏览器
     */
    protected function _check_browser()
    {
        $browser = 'Firefox';
        $version = '27.00';

        $user_agent =& load_class('User_agent', 'libraries');
        if( ! $user_agent->is_browser($browser) OR version_compare($user_agent->version(), $version, '<'))
        {
            $data = array(
                'user_browser' => $user_agent->browser(),
                'user_version' => $user_agent->version(),
                'user_os'      => $user_agent->platform,

                'browser'      => $browser,
                'version'      => $version,
                'os'           => 'Windows 7',
            );

            // 显示浏览器错误页面
            echo $this->_error->show_error('浏览器验证失败.', $data, 'error_browser', 200);
            exit;
        }
    }

    /**
     * 检测权限
     */
    protected function _check_priv()
    {
       
        // 没有登陆, 去登陆
        if( FALSE === $resource = login_info('resource'))
        {
            header("Location: ".DOMAIN.'home/login', TRUE, 302);
            exit;
        }
        // 是否验证权限
        if( $this->_check_priv === TRUE)
        {
            // 没有权限。不允许
            if( ! in_array($this->_key, $this->_public) && ! isset($resource['priv'][$this->_key]) )
            {
                if( $this->_input->is_ajax_request() )
                {
                    header('Content-Type: application/json');
                    exit(json_encode(array(
                        'msg'    => "您没有权限访问此模块, {$this->_key}",
                        'status' => false,
                    )));
                }
                else
                {
                    echo $this->_error->show_error('您没有权限访问此模块',array("Permission: ".$this->_key), 'error_access',200);
                    exit;
                }
            }
        }
    }

    /**
     * [记录面包屑信息]
     * @return void
     */
    private function _record_breadcrumb()
    {
        $resource = login_info('resource');
        $menu     = $resource['menu'];

        $this->_recursive_search_menu($menu, $this->_key);
    }

    /**
     * [递归遍历菜单，搜索面包屑]
     */
    private function _recursive_search_menu($menu, $key, $append = array(), $n = 0)
    {
        if( ! $menu || ! $key)
            return;

        foreach ($menu as $m) 
        {
            $append[] = $m['name'];

            if( $m['url'] === $key )
            {
                $_SESSION['breadcrumb'] = $append;
                return;
            }

            if( $m['children'] )
            {
                $this->_recursive_search_menu($m['children'], $key, $append, $n+1);
            }
            else
            {
                array_pop($append);
            }

            if($n === 0)
            {
                $append = array();
            }
        }
    }
}

/* End of file.php */